import logging

from pymysql.cursors import DictCursor

from src.python.db.base import mysqlpool

logging.basicConfig(format='%(asctime)s %(levelname)8s: %(message)s', datefmt='%m-%d %H:%M:%S')
logger = logging.getLogger(__name__)
logger.setLevel('WARNING')


###############################################################################
# MysqlConnection  ############################################################
###############################################################################


class MysqlConnectionConfig(object):
    def __init__(self, host: str = "localhost", port: int = 3306, user: str = "root", password: str = "sanmubird",
                 database: str = "aps"):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.database = database

    def to_dict(self) -> dict:
        return {
            'host': self.host
            , 'port': self.port
            , 'user': self.user
            , 'password': self.password
            , 'database': self.database
        }


def get_local_db_config() -> dict:
    return MysqlConnectionConfig().to_dict()


config = get_local_db_config()
pool = mysqlpool.ConnectionPool(**config)


def select(sql, args, size=None):
    with pool.get_connection() as conn:
        with conn.cursor(DictCursor) as cur:
            cur.execute(sql.replace('?', '%s'), args or ())
            if size:
                rs = cur.fetchmany(size)
            else:
                rs = cur.fetchall()
        logging.info('rows returned: %s' % len(rs))
        return rs


def execute(sql, args, autocommit=True):
    with pool.get_connection() as conn:
        if not autocommit:
            conn.begin()
        try:
            with conn.cursor() as cur:
                cur.execute(sql.replace('?', '%s'), args)
                affected = cur.rowcount
            if not autocommit:
                conn.commit()
        except BaseException as e:
            if not autocommit:
                conn.rollback()
            raise
        return affected


###############################################################################
# ORM  ########################################################################
###############################################################################

def create_args_string(num):
    _list = []
    for i in range(num):
        _list.append('?')
    return ', '.join(_list)


class Field(object):

    def __init__(self, name, column_type, default, primary_key: bool = False):
        self.name = name
        self.column_type = column_type
        self.primary_key = primary_key
        self.default = default

    def __str__(self):
        return '<%s, %s:%s>' % (self.__class__.__name__, self.column_type, self.name)


class StringField(Field):

    def __init__(self, name=None, primary_key=False, default=None, ddl='varchar(100)'):
        super().__init__(name, ddl, default, primary_key)


class BooleanField(Field):

    def __init__(self, name=None, default=False):
        super().__init__(name, 'boolean', default, False)


class IntegerField(Field):

    def __init__(self, name=None, default=0, primary_key=False):
        super().__init__(name, 'bigint', default, primary_key)


class FloatField(Field):

    def __init__(self, name=None, default=0.0, primary_key=False):
        super().__init__(name, 'real', default, primary_key)


class TextField(Field):

    def __init__(self, name=None, default=None):
        super().__init__(name, 'text', default, False)


class ModelMetaclass(type):

    def __new__(cls, name, bases, attrs):
        # 排除Model类本身:
        if name == 'Model':
            return type.__new__(cls, name, bases, attrs)
        # 获取table名称:
        table_name = attrs.get('__table__', None) or name
        logging.info('found model: %s (table: %s)' % (name, table_name))
        # 获取所有的Field和主键名:
        mappings = dict()
        fields = []
        primary_key = None
        for k, v in attrs.items():
            if isinstance(v, Field):
                logging.info('  found mapping: %s ==> %s' % (k, v))
                mappings[k] = v
                if v.primary_key:
                    # 找到主键:
                    if primary_key:
                        raise RuntimeError('Duplicate primary key for field: %s' % k)
                    primary_key = k
                else:
                    fields.append(k)
        if not primary_key:
            raise RuntimeError('Primary key not found.')
        for k in mappings.keys():
            attrs.pop(k)
        escaped_fields = list(map(lambda f: f'`{f}`', fields))
        update_escaped_fields_str = ', '.join(map(lambda f: f'`{mappings.get(f).name or f}`=?', fields))
        attrs['__mappings__'] = mappings  # 保存属性和列的映射关系
        attrs['__table__'] = table_name
        attrs['__primary_key__'] = primary_key  # 主键属性名
        attrs['__fields__'] = fields  # 除主键外的属性名
        # 构造默认的SELECT, INSERT, UPDATE和DELETE语句:
        select_escaped_fields_str = ', '.join(escaped_fields)
        attrs['__select__'] = f"select `{primary_key}`, {select_escaped_fields_str} from `{table_name}`"
        attrs['__insert__'] = f"insert into `{table_name}` ({select_escaped_fields_str}, `{primary_key}`) " \
                              f"values ({create_args_string(len(escaped_fields) + 1)})"
        attrs['__update__'] = f"update `{table_name}` set {update_escaped_fields_str} where `{primary_key}` = ? "
        attrs['__delete__'] = f"delete from `{table_name}` where `{primary_key}` = ?"
        return type.__new__(cls, name, bases, attrs)


class Model(dict, metaclass=ModelMetaclass):

    def __init__(self, **kw):
        super().__init__(**kw)

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(r"'Model' object has no attribute '%s'" % key)

    def to_dict(self):
        return self

    def __setattr__(self, key, value):
        self[key] = value

    def get_value(self, key):
        return getattr(self, key, None)

    def get_value_or_default(self, key):
        value = getattr(self, key, None)
        if value is None:
            field = self.__mappings__[key]
            if field.default is not None:
                value = field.default() if callable(field.default) else field.default
                logging.debug('using default value for %s: %s' % (key, str(value)))
                setattr(self, key, value)
        return value

    @classmethod
    def find_all(cls, where=None, args=None, **kw):
        ' find objects by where clause. '
        sql = [cls.__select__]
        if where:
            sql.append('where')
            sql.append(where)
        if args is None:
            args = []
        order_by = kw.get('orderBy', None)
        if order_by:
            sql.append('order by')
            sql.append(order_by)
        limit = kw.get('limit', None)
        if limit is not None:
            sql.append('limit')
            if isinstance(limit, int):
                sql.append('?')
                args.append(limit)
            elif isinstance(limit, tuple) and len(limit) == 2:
                sql.append('?, ?')
                args.extend(limit)
            else:
                raise ValueError('Invalid limit value: %s' % str(limit))
        rs = select(' '.join(sql), args)
        return [cls(**r) for r in rs]

    @classmethod
    def find_number(cls, select_field, where=None, args=None):
        ' find number by select and where. '
        sql = [f'select count(`{select_field}`) _num_ from `{cls.__table__}`']
        if where:
            sql.append('where')
            sql.append(where)
        rs = select(' '.join(sql), args, 1)
        if len(rs) == 0:
            return None
        return rs[0]['_num_']

    @classmethod
    def find(cls, pk):
        ' find object by primary key. '
        rs = select('%s where `%s`=?' % (cls.__select__, cls.__primary_key__), [pk], 1)
        if len(rs) == 0:
            return None
        return cls(**rs[0])

    def insert(self):
        args = list(map(self.get_value_or_default, self.__fields__))
        args.append(self.get_value_or_default(self.__primary_key__))
        rows = execute(self.__insert__, args)
        if rows != 1:
            logging.warn('failed to insert record: affected rows: %s' % rows)
        return rows

    def modify(self, **kw):
        args = list(map(self.get_value, self.__fields__))
        args.append(self.get_value(self.__primary_key__))
        rows = execute(self.__update__, args)
        if rows != 1:
            logging.warn('failed to update by primary key: affected rows: %s' % rows)
        return rows

    def delete(self):
        args = [self.get_value(self.__primary_key__)]
        rows = execute(self.__delete__, args)
        if rows != 1:
            logging.warn('failed to remove by primary key: affected rows: %s' % rows)
        return rows
